import * as auth from '@/utils/auth'
import request from '@/utils/request'
import fileDownload from 'js-file-download'
import Qs from 'qs'
export const localStorage = window.localStorage
export const enableBatchOpt = false
/**
 * post请求，application/json
 * @param {*} url 请求url
 * @param {*} data json对象
 * @param {*} headers 如headers: {
                          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
                        }
                      如果不需要传递headers，则直接使用{}
 */
export const doPostJson = (url, data, headers) => {
  headers[auth.HEADER_APPID] = auth.APPID
  if (auth.APP_AUTH_ENABLE) {
    headers[auth.HEADER_REQURL] = url
    const timestamp = new Date().getTime()
    const nonceStr = uuid()
    headers[auth.HEADER_TIMESTAMP] = timestamp
    headers[auth.HEADER_NONCESTR] = nonceStr
    headers[auth.HEADER_SIGN] = auth.generateSignJson(url, timestamp, nonceStr, data)
  }
  return request({
    url: url,
    method: 'POST',
    data: data,
    headers: headers
  })
}

/**
 * post请求，application/x-www-form-urlencoded
 * @param {*} url 请求url
 * @param {*} data json对象
 * @param {*} headers 如headers: {
                          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
                        }
                      如果不需要传递headers，则直接使用{}
 */
export const doPostQs = (url, data, headers) => {
  headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
  headers[auth.HEADER_APPID] = auth.APPID
  if (auth.APP_AUTH_ENABLE) {
    headers[auth.HEADER_REQURL] = url
    const timestamp = new Date().getTime()
    const nonceStr = uuid()
    headers[auth.HEADER_TIMESTAMP] = timestamp
    headers[auth.HEADER_NONCESTR] = nonceStr
    headers[auth.HEADER_SIGN] = auth.generateSignQs(url, timestamp, nonceStr, data)
  }
  return request({
    url: url,
    method: 'POST',
    data: Qs.stringify(data, { arrayFormat: 'repeat' }),
    headers: headers
  })
}

/**
 * post请求，application/x-www-form-urlencoded，返回arraybuffer数据，如图片
 * @param {*} url 请求url
 * @param {*} data json对象
 * @param {*} headers 如headers: {
                          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
                        }
                      如果不需要传递headers，则直接使用{}
 */
export const doPostQsArrayBuffer = (url, data, headers) => {
  headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
  headers[auth.HEADER_APPID] = auth.APPID
  if (auth.APP_AUTH_ENABLE) {
    headers[auth.HEADER_REQURL] = url
    const timestamp = new Date().getTime()
    const nonceStr = uuid()
    headers[auth.HEADER_TIMESTAMP] = timestamp
    headers[auth.HEADER_NONCESTR] = nonceStr
    headers[auth.HEADER_SIGN] = auth.generateSignQs(url, timestamp, nonceStr, data)
  }
  return request({
    url: url,
    method: 'POST',
    data: Qs.stringify(data, { arrayFormat: 'repeat' }),
    headers: headers,
    responseType: 'arraybuffer'
  })
}

/**
*  post请求，application/x-www-form-urlencoded，返回arraybuffer数据，如图片
* @param self this
*/
export const doPostQsBlob = (url, data, headers) => {
  headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
  headers[auth.HEADER_APPID] = auth.APPID
  if (auth.APP_AUTH_ENABLE) {
    headers[auth.HEADER_REQURL] = url
    const timestamp = new Date().getTime()
    const nonceStr = uuid()
    headers[auth.HEADER_TIMESTAMP] = timestamp
    headers[auth.HEADER_NONCESTR] = nonceStr
    headers[auth.HEADER_SIGN] = auth.generateSignQs(url, timestamp, nonceStr, data)
  }
  return request({
    url: url,
    method: 'POST',
    data: Qs.stringify(data, { arrayFormat: 'repeat' }),
    headers: headers,
    responseType: 'blob'
  })
}

/**
 * get请求
 * @param {*} url 请求url，包含请求参数
 * @param {*} headers 如headers: {
                          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
                        }
                      如果不需要传递headers，则直接使用{}
 */
export const doGet = (url, headers) => {
  headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
  headers[auth.HEADER_APPID] = auth.APPID
  if (auth.APP_AUTH_ENABLE) {
    headers[auth.HEADER_REQURL] = url.indexOf('?') > 0 ? url.split('?')[0] : url
    const timestamp = new Date().getTime()
    const nonceStr = uuid()
    headers[auth.HEADER_TIMESTAMP] = timestamp
    headers[auth.HEADER_NONCESTR] = nonceStr
    headers[auth.HEADER_SIGN] = auth.generateSignGet(url, timestamp, nonceStr)
  }
  return request({
    url: url,
    method: 'GET',
    headers: headers
  })
}

/**
 * 上传图片到指定服务器，返回图片服务器端路径
 * @param {*} url
 * @param {*} formData
 * @param {*} headers
 */
export const uploadFile = (url, formData, headers) => {
  headers['Content-Type'] = 'multipart/form-data'
  return request({
    url: url,
    method: 'POST',
    data: formData,
    headers: headers
  })
}

/**
 * @param options
 * options = {
 *  mainComponent: this,
 *  dialogRef: dialogRef,
 *  formRef: formRef,
 *  url: url,
 *  tableRef: tableRef
 * }
 */
export const add = (options) => {
  return new Promise((resolve, reject) => {
    const self = options.mainComponent
    let dialogRef = options.dialogRef
    if (!dialogRef) {
      dialogRef = 'addEditDialog'
    }
    let formRef = options.formRef
    if (!formRef) {
      formRef = 'addForm'
    }
    let tableRef = options.tableRef
    if (!tableRef) {
      tableRef = 'table'
    }
    const addEditDialog = self.$refs[dialogRef]
    const addForm = addEditDialog.$refs[formRef]
    addForm.validate(valid => {
      if (valid) {
        addEditDialog.loading.add = true
        doPostJson(options.url, addEditDialog.form, {}).then(response => {
          const data = response
          self.$message.success(data.message)
          addEditDialog.loading.add = false
          addEditDialog.dialog.add = false
          const tableComponent = self.$refs[tableRef]
          tableComponent.search()
          resolve(response)
        }).catch(error => {
          addEditDialog.loading.add = false
          reject(error)
        })
      }
    })
  })
}

/**
 * @param options
 * options = {
 *  mainComponent: this,
 *  dialogRef: dialogRef,
 *  formRef: formRef,
 *  url: url,
 *  tableRef: tableRef
 * }
 */
export const edit = (options) => {
  return new Promise((resolve, reject) => {
    const self = options.mainComponent
    let dialogRef = options.dialogRef
    if (!dialogRef) {
      dialogRef = 'addEditDialog'
    }
    let formRef = options.formRef
    if (!formRef) {
      formRef = 'editForm'
    }
    let tableRef = options.tableRef
    if (!tableRef) {
      tableRef = 'table'
    }
    const addEditDialog = self.$refs[dialogRef]
    const editForm = addEditDialog.$refs[formRef]
    editForm.validate(valid => {
      if (valid) {
        addEditDialog.loading.edit = true
        doPostJson(options.url, addEditDialog.form, {}).then(response => {
          const data = response
          self.$message.success(data.message)
          addEditDialog.loading.edit = false
          addEditDialog.dialog.edit = false
          const tableComponent = self.$refs[tableRef]
          tableComponent.search()
          resolve(response)
        }).catch(error => {
          addEditDialog.loading.edit = false
          reject(error)
        })
      }
    })
  })
}

/**
 * @param options
 * options = {
 *  tableComponent: tableComponent,
 *  url: url
 * }
 */
export const remove = (options) => {
  return new Promise((resolve, reject) => {
    const tableComponent = options.tableComponent
    tableComponent.$confirm('确认删除选择的数据吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      doGet(options.url, {}).then(response => {
        tableComponent.$message.success('已删除选择的数据')
        tableComponent.search()
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    }).catch(() => { })
  })
}

/**
 * @param options
 * options = {
 *  mainComponent: mainComponent,
 *  tableRef: tableRef,
 *  url: url
 * }
 */
export const batchRemove = (options) => {
  return new Promise((resolve, reject) => {
    const self = options.mainComponent
    let tableRef = options.tableRef
    if (!tableRef) {
      tableRef = 'table'
    }
    const tableComponent = self.$refs[tableRef]
    if (tableComponent.table.allSelection.length === 0) {
      self.$message.warning('请选择需要批量删除的数据')
    } else {
      self.$confirm('确认删除选择的数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = []
        tableComponent.table.allSelection.forEach((row, index) => {
          ids.push(row.id)
        })
        doPostJson(options.url, ids, {}).then(response => {
          self.$message.success(response.message)
          tableComponent.table.allSelection = []
          tableComponent.search()
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      }).catch(() => { })
    }
  })
}

/**
 * @param options
 * options = {
 *  tableComponent: tableComponent,
 *  url: url,
 *  row: row
 * }
 */
export const active = (options) => {
  return new Promise((resolve, reject) => {
    const tableComponent = options.tableComponent
    const isActive = options.row.isActive === 0 ? 1 : 0
    const data = {
      id: options.row.id,
      isActive: isActive
    }
    doPostJson(options.url, data, {}).then(response => {
      tableComponent.$message.success(response.message)
      tableComponent.search()
      resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
}

/**
 * @param options
 * options = {
 *  mainComponent: mainComponent,
 *  tableRef: tableRef,
 *  url: url,
 *  isActive: 0
 * }
 */
export const batchActive = (options) => {
  return new Promise((resolve, reject) => {
    const self = options.mainComponent
    let tableRef = options.tableRef
    if (!tableRef) {
      tableRef = 'table'
    }
    const tableComponent = self.$refs[tableRef]
    const rowArray = []
    if (tableComponent.table.allSelection.length === 0) {
      self.$message.warning('请选择需要批量' + (options.isActive === 1 ? '激活' : '冻结') + '的数据')
    } else {
      tableComponent.table.allSelection.forEach((row, index) => {
        if (row.isActive !== options.isActive) {
          rowArray.push({
            id: row.id,
            isActive: options.isActive
          })
        }
      })
      if (rowArray.length > 0) {
        doPostJson(options.url, rowArray, {}).then(response => {
          self.$message.success(response.message)
          tableComponent.table.allSelection = []
          tableComponent.search()
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      } else {
        self.$message.warning('没有需要批量' + (options.isActive === 1 ? '激活' : '冻结') + '的数据')
      }
    }
  })
}

/**
 * 根据searchForm分页搜索
 *
 * @param options
 * options = {
 *  mainComponent: this,
 *  searchDialogRef: searchDialogRef,
 *  formRef: formRef,
 *  url: url,
 *  tableRef: tableRef,
 *  resetSearch: false,
 *  clearOldSelection: false,
 *  idProp: idProp
 * }
 *
 */
export const search = (options) => {
  return new Promise((resolve, reject) => {
    const self = options.mainComponent
    let searchDialogRef = options.searchDialogRef
    if (!searchDialogRef) {
      searchDialogRef = 'searchDialog'
    }
    let formRef = options.formRef
    if (!formRef) {
      formRef = 'searchForm'
    }
    let tableRef = options.tableRef
    if (!tableRef) {
      tableRef = 'table'
    }
    let resetSearch = options.resetSearch
    if (!resetSearch) {
      resetSearch = false
    }
    let clearOldSelection = options.clearOldSelection
    if (!clearOldSelection) {
      clearOldSelection = false
    }
    const tableComponent = self.$refs[tableRef]
    const searchDialog = self.$refs[searchDialogRef]
    setCurrentSearchType(tableComponent, searchDialogRef)
    setSearchForm(tableComponent, searchDialog, resetSearch)
    doClearOldSelection(tableComponent, clearOldSelection)
    searchDialog.loading.search = true
    tableComponent.table.loading = true
    getDataDict(tableComponent.dataDictCodes).then(response => {
      tableComponent.dataDictItems = response
      doPostJson(options.url, searchDialog.searchForm, {}).then(response => {
        tableComponent.pager.total = response.data.total
        tableComponent.table.tableRows = response.data.rows
        let id = 'id'
        if (options.idProp) {
          id = options.idProp
        }
        self.$nextTick(() => {
          selectSelectedData(tableComponent, id)
          selectExistData(tableComponent, id)
        })
        searchDialog.loading.search = false
        tableComponent.table.loading = false
        resolve(response)
      }).catch(error => {
        searchDialog.loading.search = false
        tableComponent.table.loading = false
        reject(error)
      })
    }).catch(error => {
      console.log(error)
    })
  })
}

const setSearchForm = (tableComponent, searchDialog, resetSearch) => {
  if (resetSearch) {
    tableComponent.pager.pageNo = 1
    tableComponent.pager.pageSize = 10
    tableComponent.searchOpts.sortColumn = null
    tableComponent.searchOpts.sortOrder = null
    tableComponent.$refs.dataTable.clearSort()
  }
  searchDialog.searchForm.pageNo = tableComponent.pager.pageNo
  searchDialog.searchForm.pageSize = tableComponent.pager.pageSize
  searchDialog.searchForm.sortColumn = tableComponent.searchOpts.sortColumn
  searchDialog.searchForm.sortOrder = tableComponent.searchOpts.sortOrder
}

const doClearOldSelection = (tableComponent, clearOldSelection) => {
  if (clearOldSelection) {
    if (tableComponent.table.allSelection && tableComponent.table.allSelection.length > 0) {
      tableComponent.table.allSelection = []
    } else if (tableComponent.table.currentRow) {
      tableComponent.table.currentRow = {}
      // 清除单选数据的选中状态
      tableComponent.$refs.dataTable.setCurrentRow()
    }
  }
}

const setCurrentSearchType = (tableComponent, searchDialogRef) => {
  if (searchDialogRef === 'searchDialog') {
    tableComponent.searchType = 'advance'
  } else if (searchDialogRef === 'quickSearch') {
    tableComponent.searchType = 'quick'
  }
}

/**
 * 勾选上表格中原先被勾选的数据，如翻页时，排序时，刷新时,
 * @param {*} tableComponent
 * @param {*} idProp
 */
const selectSelectedData = (tableComponent, idProp) => {
  if (tableComponent.table.allSelection.length > 0) {
    for (const selectionIndex in tableComponent.table.allSelection) {
      const selectionData = tableComponent.table.allSelection[selectionIndex]
      for (const tableRowIndex in tableComponent.table.tableRows) {
        const tableRowData = tableComponent.table.tableRows[tableRowIndex]
        if (selectionData[idProp] === tableRowData[idProp]) {
          tableComponent.$refs.dataTable.toggleRowSelection(tableRowData, true)
          break
        }
      }
    }
  } else if (tableComponent.table.currentRow && JSON.stringify(tableComponent.table.currentRow) !== '{}') {
    for (const tableRowIndex in tableComponent.table.tableRows) {
      const tableRowData = tableComponent.table.tableRows[tableRowIndex]
      if (tableComponent.table.currentRow[idProp] === tableRowData[idProp]) {
        tableComponent.$refs.dataTable.setCurrentRow(tableRowData)
        break
      }
    }
  }
}

/**
 * 勾选上数据库中已经存在的数据
 * @param {*} tableComponent
 * @param {*} idProp
 */
const selectExistData = (tableComponent, idProp = 'id') => {
  if (tableComponent.selectedData && tableComponent.selectedData.length > 0) {
    for (const selectedDataIndex in tableComponent.selectedData) {
      const selectedDataRow = tableComponent.selectedData[selectedDataIndex]
      for (const rowIndex in tableComponent.table.tableRows) {
        const row = tableComponent.table.tableRows[rowIndex]
        if (selectedDataRow[tableComponent.selectedDataIdProp] === row[idProp]) {
          tableComponent.$refs.dataTable.toggleRowSelection(row, true)
          // 设置该条数据已被选择
          tableComponent.$refs.dataTable.setCurrentRow(row)
          // 但是当前并没有选择新数据
          tableComponent.table.currentRow = {}
        }
        selectable(tableComponent, row, idProp)
      }
    }
  }
}

/**
 * table表格选中事件处理，选中某行
 * @param tableComponent table组件
 * @param selections 事件返回值
 * @param row
 */
export const select = (tableComponent, selection, row) => {
  tableComponent.table.allSelection = []
  if (selection.length > 0) {
    tableComponent.table.pageSelection['page_' + tableComponent.pager.pageNo] = selection
  } else {
    delete tableComponent.table.pageSelection['page_' + tableComponent.pager.pageNo]
  }
  for (const key in tableComponent.table.pageSelection) {
    const selection = tableComponent.table.pageSelection[key]
    if (selection.length > 0) {
      tableComponent.table.allSelection = tableComponent.table.allSelection.concat(selection)
    }
  }
}

/**
 * table表格选中事件处理，记录所有被选中的项
 * @param tableComponent table组件
 * @param selections 事件返回值
 * @param idProp 指明表格的id属性
 */
export const selectAll = (tableComponent, selection) => {
  tableComponent.table.allSelection = []
  if (selection.length > 0) {
    tableComponent.table.pageSelection['page_' + tableComponent.pager.pageNo] = selection
  } else {
    delete tableComponent.table.pageSelection['page_' + tableComponent.pager.pageNo]
  }
  for (const key in tableComponent.table.pageSelection) {
    const selection = tableComponent.table.pageSelection[key]
    if (selection.length > 0) {
      tableComponent.table.allSelection = tableComponent.table.allSelection.concat(selection)
    }
  }
}

/**
 * 判断数据是否原先就已经存在，如果是，则禁用此数据的勾选
 * @param {*} tableComponent
 * @param {*} row
 * @param {*} idProp
 */
export const selectable = (tableComponent, row, idProp = 'id') => {
  if (tableComponent.selectedData && tableComponent.selectedData.length > 0) {
    for (const selectedDataIndex in tableComponent.selectedData) {
      const selectedDataRow = tableComponent.selectedData[selectedDataIndex]
      if (selectedDataRow[tableComponent.selectedDataIdProp] === row[idProp]) {
        return false
      }
    }
  }
  return true
}

/**
 * 表格单选
 * @param {*} tableComponent
 * @param {*} currentRow
 * @param {*} oldCurrentRow
 */
export const changeCurrent = (tableComponent, currentRow, oldCurrentRow) => {
  tableComponent.table.currentRow = currentRow
}

/**
 * table表格排序事件处理
 * @param tableComponent table组件
 * @param sortColumn 排序字段信息
 */
export const changeSort = (tableComponent, sortColumn) => {
  if (!sortColumn.order) {
    tableComponent.searchOpts.sortColumn = ''
    tableComponent.searchOpts.sortOrder = ''
  } else {
    tableComponent.searchOpts.sortColumn = sortColumn.prop
    tableComponent.searchOpts.sortOrder = sortColumn.order === 'ascending' ? 'asc' : 'desc'
  }
  tableComponent.search()
}

/**
 * 分页组件页码改变事件处理
 * @param tableComponent table组件
 * @param pageNo 修改后的页码
 */
export const changePageNo = (tableComponent, pageNo) => {
  tableComponent.pager.pageNo = pageNo
  tableComponent.search()
}

/**
 * 分页组件每页大小改变事件处理
 * @param tableComponent table组件
 * @param pageSize 修改后的每页大小
 */
export const changePageSize = (tableComponent, pageSize) => {
  tableComponent.pager.pageSize = pageSize
  tableComponent.search()
}

/**
 * 根据指定的多个数据字典的code获取多个数据字典项的值，并缓存到前端
 * @param {*} dictCodes 如 ['IS_ACTIVE', 'PAYMENT_TYPE']
 */
export const getDataDict = (dictCodes) => {
  const dataDictItems = {}
  const dictCodesWithNoItems = []
  return new Promise((resolve, reject) => {
    if (!dictCodes || dictCodes.length === 0) {
      resolve(dataDictItems)
      return
    }
    dictCodes.forEach(dictCode => {
      const dictItems = localStorage.getItem(dictCode)
      if (dictItems !== null && dictItems !== undefined && dictItems !== 'undefined') {
        dataDictItems[dictCode] = JSON.parse(dictItems)
      } else {
        dictCodesWithNoItems.push(dictCode)
      }
    })
    if (dictCodesWithNoItems.length <= 0) {
      resolve(dataDictItems)
    } else {
      doPostJson('/data-dict-item/any/by-dict-codes', dictCodesWithNoItems, {}).then(response => {
        dictCodesWithNoItems.forEach(dictCode => {
          localStorage.setItem(dictCode, JSON.stringify(response.data[dictCode]))
          dataDictItems[dictCode] = response.data[dictCode]
        })
        resolve(dataDictItems)
      }).catch(error => {
        reject(error)
      })
    }
  })
}

/**
 * 获取表格中数据字典项
 * options = {
 *  dataDictItems: dataDictItems,
 *  dictCode: dictCode,
 *  value: value
 * }
 */
export const getDataDictItemDisplayValue = (options) => {
  const dictItems = options.dataDictItems[options.dictCode]
  if (!dictItems) {
    return {
      displayValue: options.value
    }
  }
  if (options.value !== null && options.value !== undefined && options.value !== '') {
    for (let i = 0, len = dictItems.length; i < len; i++) {
      if (options.value === dictItems[i].value) {
        return dictItems[i]
      }
    }
  }
  return {
    displayValue: options.value
  }
}

/**
 * 从指定的数据字典中获取下拉菜单显示的数据，把默认值
 * options = {
 *  mainComponent: mainComponent,
 *  dataDictItems: dataDictItems,
 *  dictCode: dictCode,
 *  formProp: formProp,
 *  dataProp: dataProp
 * }
 */
export const getSelectDictItems = (options) => {
  const self = options.mainComponent
  const dictItems = options.dataDictItems[options.dictCode]
  if (dictItems && dictItems.length > 0) {
    self.selects[options.dataProp] = dictItems
    const itemValue = dictItems[0].value
    if (itemValue === null || itemValue === undefined || itemValue === '') {
      // 如果数据项值是空的，则需要把显示的中文值赋值给value
      self.selects[options.dataProp].forEach(item => {
        item.value = item.displayValue
      })
    }
    if (self.form) {
      // 只有添加和编辑下拉菜单需要有下拉默认值
      for (let i = 0, len = dictItems.length; i < len; i++) {
        const item = dictItems[i]
        if (item.isDefault === 1) {
          self.form[options.formProp] = item.value
          break
        }
      }
    }
  }
}

/**
 * 获取详情中数据字典项的显示值
 * options = {
 *  mainComponent: mainComponent,
 *  dataDictItems: dataDictItems,
 *  dictCode: dictCode,
 *  formProp: formProp
 * }
 */
export const getDetailDictItemDisplayValue = (options) => {
  const self = options.mainComponent
  const dictItems = options.dataDictItems[options.dictCode]
  if (dictItems !== null && dictItems !== undefined && dictItems !== 'undefined') {
    for (let i = 0, len = dictItems.length; i < len; i++) {
      if (self.form[options.formProp] === dictItems[i].value) {
        self.form[options.formProp] = dictItems[i].displayValue
        break
      }
    }
  }
}

/**
 * 导出文件
 * @param self this
 */
export const exportFile = (options) => {
  let self = options.self
  self.$message.warning('文件导出中，请勿重复导出...')
  doPostQsBlob(options.url, {}, {}).then(response => {
    fileDownload(response.data, options.filename)
    self.$message.success('文件导出成功')
  }).catch(error => {
    console.log(error)
    self.$message.error('导出文件失败，稍候再试')
  })
}

/**
 * 取指定多少天前或多少天后的时间
 * getDate(7)：7天后的时间
 * getDate(-7)：7天前的时间
 */
export const getDate = (date1, days) => {
  var time1 =
    date1.getFullYear() +
    '-' +
    (date1.getMonth() + 1) +
    '-' +
    date1.getDate()
  var date2 = new Date(date1)
  date2.setDate(date1.getDate() + days)
  var time2 =
    date2.getFullYear() +
    '-' +
    ((date2.getMonth() + 1) < 10 ? '0' + (date2.getMonth() + 1) : (date2.getMonth() + 1)) +
    '-' +
    (date2.getDate() < 10 ? '0' + date2.getDate() : date2.getDate())
  return time2
}

/**
 * 读取arrayBuffer数据到FileReader对象中，FileReader中存储字符串
 * @param {*} arrayBufferData
 */
export const arrayBufferToReader = (arrayBufferData) => {
  const blob = new Blob([arrayBufferData])
  const reader = new FileReader()
  reader.readAsText(blob, 'utf-8')
  return reader
}

/**
 * 把arrayBuffer数据转化成指定类型的图片
 * @param {*} imageType
 * @param {*} arrayBufferData
 */
export const arrayBufferToImage = (imageType, arrayBufferData) => {
  return 'data:image/' + imageType + ';base64,' + btoa(
    new Uint8Array(arrayBufferData).reduce((data, byte) => data + String.fromCharCode(byte), '')
  )
}

export const uuid = () => {
  const s = []
  const hexDigits = '0123456789abcdef'
  for (let i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = '-'
  const uuid = s.join('')
  return uuid
}
